package com.mc.web;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.mc.model.Path;
import com.mc.model.User;
import com.mc.model.newsandbulletin;
import com.mc.service.NewsandbulletService;
import com.mc.utils.PathUtil;
import com.mc.utils.StringUtil;

@Controller
@RequestMapping("/backend")
@SessionAttributes("user")
public class NewsAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(NewsAction.class);
	private static String PREFIX = "";
	private Path path = null;
	
	@Autowired NewsandbulletService newsandbulletService;
	/**
	 * 
	 * @param modelMap
	 * @return  返回用于添加新闻、公告的页面
	 */
	@RequestMapping("/addnewsui")
   public String addnewsui(ModelMap modelMap)
   {
		path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:addnews","ViewTitle:添加新闻公告","smenu:newsandbullet","mmenu:addnews"});				
		return PathUtil.returnStr(path, modelMap);
   }
	/**
	 * 
	 * @param nb  前台读到的新闻类对象数据
	 * @param modelMap  传输数据的对象
	 * @param session session
	 * @param request request
	 * @return  按照要求添加新闻、公告
	 */
	@RequestMapping("/addnews")
   public String addnews(newsandbulletin nb,ModelMap modelMap,HttpSession session,HttpServletRequest request)
   {
		logger.info(nb.toString());
		String path = request.getContextPath();
		String IP = "";
		//IP ip = new ipad
		InetAddress ia = null;
		try {
			ia = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}   
      //  String host = ia.getHostName();//获取计算机主机名  
         IP= ia.getHostAddress();//获取计算机IP  
		String basePath = path + "/ueditor/jsp/";
		
		//nb.setIndex(0);
		List<String>filepath = StringUtil.getInstace().getFilepaths();
	//	logger.info(filepath);
		
		String fp1 = "";
		for(String fp : filepath)
		{
			if(nb.getContent().contains(fp))
			{
				fp1 =  fp;
				nb.setUrl(basePath + fp1);
				nb.setIndex(1);
				break;
			}
		}
		
	//	logger.info(basePath + fp1 + "----url");
		nb.setAuthor((User)session.getAttribute("user"));
	   //logger.info(nb.toString());
	   
	   newsandbulletService.insertNorB(nb);
	   modelMap.addAttribute("message", true);
	   return "forward:/backend/newsmagui";
   }
	 /**
	  * 
	  * @param modelMap
	  * @return   返回用于管理新闻、公告的页面
	  */
	@RequestMapping("/newsmagui")
	public String newsmag(ModelMap modelMap)
	{  
		path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:newsmag","ViewTitle:新闻公告管理","smenu:newsandbullet","mmenu:newsmag"});				
		 
	    List<newsandbulletin> bulletins =newsandbulletService.selectAllBulletin();
		int newsesCount = newsandbulletService.selectAllNewsCount();
	    List<newsandbulletin> newses = newsandbulletService.selectAllNews();
	  
	  //  logger.info(bulletins.get(0).getId()+","+bulletins.get(0).getIndex());
		int bulletinsCount = newsandbulletService.selectAllBulletinCount();
	    modelMap.addAttribute("bulletins",bulletins);
		modelMap.addAttribute("newsesCount", newsesCount);
	    modelMap.addAttribute("newses",newses);
		modelMap.addAttribute("bulletinsCount", bulletinsCount);
		return PathUtil.returnStr(path, modelMap);
		
	}
	/**
	 * 
	 * @param id  需要删除的新闻、公告id
	 * @param requst 用于请求前台跨域ajax要接收返回数据的js函数
	 * @return ajax返回前台
	 */
	@RequestMapping("/deletenbs")
	@ResponseBody
	public String deletenbs(@RequestParam(value="id",required=true) int id,
			HttpServletRequest request)
	{
		logger.info(id);
		int result = newsandbulletService.deleteByPrimaryKey(id);
		String callbackFunName = request.getParameter("callbackparam");
		 if(result !=0)
		 {
			 
			 return callbackFunName +"("+ "{'success':true}" +")";
		 }else{
			 //modelMap.addAttribute("delFile", false);
			 return callbackFunName +"("+ "{'success':false}" +")";
		 }
	}
	/**
	 * 
	 * @param modelMap
	 * @param nid  新闻、公告id
	 * @return 返回新闻公告的详细信息
	 */
	@RequestMapping("/newsdetail/{id}")
	public String newsdetail(ModelMap modelMap,@PathVariable("id") int nid)
	{
		
		
		newsandbulletin news = newsandbulletService.selectByPrimaryKey(nid);
		modelMap.addAttribute("news",news);
		path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:NewsDetail","ViewTitle:新闻公告详细","smenu:newsandbullet","mmenu:newsdetail"});
		return PathUtil.returnStr(path, modelMap);
	}
	
	/**
	 * 
	 * @param id  需要更新的新闻、公告id
	 * @param modelMap
	 * @return 返回更新新闻、公告的页面
	 */
	@RequestMapping("/updatenewui/{id}")
	public String updatenewui(@PathVariable("id") int id,ModelMap modelMap)
	{
		newsandbulletin nb = newsandbulletService.selectByPrimaryKey(id);
		if(nb.getContent()!=null && !nb.getContent().equals("") )
			nb.setContent(StringUtil.getInstace().zy(nb.getContent()));
		modelMap.addAttribute("news", nb);
		path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:updateNews","ViewTitle:修改新闻公告","smenu:newsandbullet","mmenu:updatenews"});
		return PathUtil.returnStr(path, modelMap);
	}
	/**
	 * 
	 * @param id   需要修改的新闻、公告id
	 * @param modelMap  modelMap用于进行前台与后台数据传输的
	 * @param nb  前台管理员输入的装在新闻公告对象的数据
	 * @param session  session
	 * @param request request
	 * @return
	 */
	@RequestMapping("/updatenew/{id}")
	public String updatenew(@PathVariable("id")int id,ModelMap modelMap,newsandbulletin nb,HttpSession session,HttpServletRequest request)
	{
		logger.info(nb.toString());
		String path = request.getContextPath();
		String IP = "";
		InetAddress ia = null;
		try {
			ia = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}   
         IP= ia.getHostAddress();//获取计算机IP  
		String basePath = path + "/ueditor/jsp/";
		newsandbulletin nb1 = newsandbulletService.selectByPrimaryKey(id);
		if(nb1.getUrl()==null)
		{
			List<String>filepath = StringUtil.getInstace().getFilepaths();
				String fp1 = "";
				for(String fp : filepath)
				{
					
					if(nb.getContent().contains(fp))
					{
						fp1 =  fp;
						nb.setUrl(basePath + fp1);
						nb.setIndex(1);
						break;
					}else{
						
					}
				}
		}else{
			if(!nb.getContent().contains(nb1.getUrl()) )
			{
				List<String>filepath = StringUtil.getInstace().getFilepaths();
					String fp1 = "";
					for(String fp : filepath)
					{
						
						if(nb.getContent().contains(fp))
						{
							fp1 =  fp;
							nb.setUrl(basePath + fp1);
							nb.setIndex(1);
							break;
						}
					}
					if(fp1.equals(""))
					{
						nb.setUrl("");
						nb.setIndex(0);
					}
					
			}
		}
		nb.setId(id);
		//logger.info(nb.toString());
		User u = (User)session.getAttribute("user");
		nb.setAuthor(u);
	    newsandbulletService.updateNorB(nb);
	   
	    
	    modelMap.addAttribute("success",true);
	    return "forward:/backend/newsmagui";
	}
	/**
	 * 
	 * @param id   要置顶的公告id
	 * @param request requst用于请求前台跨域ajax要接收返回数据的js函数
	 * @return ajax返回前台
	 */
	@RequestMapping("/totopb")
	@ResponseBody
	public String totopb(@RequestParam(value="id",required=true) int id,HttpServletRequest request)
	{
		//logger.info(id);
    	int result = newsandbulletService.countoftopb();
    	String callbackFunName = request.getParameter("callbackparam");
		 if(result < 3)
		 {
			 newsandbulletService.settopnbbytype("bulletin", id);
			 return callbackFunName +"("+ "{'success':true}" +")";
		 }else{
			 //modelMap.addAttribute("delFile", false);
			 return callbackFunName +"("+ "{'success':false}" +")";
		 }
		
		
		
	}
	/**
	 * 
	 * @param id  要取消置顶的公告id
	 * @param request   requst用于请求前台跨域ajax要接收返回数据的js函数
	 * @return ajax返回前台
	 */
	@RequestMapping("/canceltopb")
	@ResponseBody
	public String canceltopb(@RequestParam(value="id",required=true) int id
			,HttpServletRequest request)
	{
		//logger.info(id);
		newsandbulletService.canceltopnbbytype("bulletin", id);
		String callbackFunName = request.getParameter("callbackparam");
		return callbackFunName +"("+ "{'success':true}" +")";
		
	}
	/**
	 * 
	 * @param id  需要在首页置顶显示的新闻id
	 * @param requst 用于请求前台跨域ajax要接收返回数据的js函数
	 * @return ajax返回前台
	 */
	@RequestMapping("/totopn")
	@ResponseBody
	public String totopn(@RequestParam(value="id",required=true) int id,
			HttpServletRequest request)
	{
		//logger.info(id);
    	int result = newsandbulletService.countoftopn();
    	String callbackFunName = request.getParameter("callbackparam");
    	if(result < 5)
		 {
    		 newsandbulletService.settopnbbytype("news", id);
			 return callbackFunName +"("+ "{'success':true}" +")";
		 }else{
			 //modelMap.addAttribute("delFile", false);
			 return callbackFunName +"("+ "{'success':false}" +")";
		 }
		
	}
	/**
	 * 
	 * @param id  需要取消在首页置顶显示的新闻id
	 * @param requst 用于请求前台跨域ajax要接收返回数据的js函数
	 * @return ajax返回前台
	 */
	@RequestMapping("/canceltopn")
	@ResponseBody
	public String canceltopn(@RequestParam(value="id",required=true) int id,
			HttpServletRequest request)
	{
		//logger.info(id);
		newsandbulletService.canceltopnbbytype("news", id);

		String callbackFunName = request.getParameter("callbackparam");
		return callbackFunName +"("+ "{'success':true}" +")";

		


		
	}
	/**
	 * 
	 * @param id  需要在首页定上面显示的新闻id
	 * @param requst 用于请求前台跨域ajax要接收返回数据的js函数
	 * @return ajax返回前台
	 */
	@RequestMapping("/setimportantnews")
	@ResponseBody
	public String setimportantnews(@RequestParam(value="id",required=true) int id,
			HttpServletRequest request)
	{
		//logger.info(id);
    	int result = newsandbulletService.countofimportantnews();
    	String callbackFunName = request.getParameter("callbackparam");
    	if(result < 5)
		 {
    		newsandbulletService.setimportantnews(id);
			 return callbackFunName +"("+ "{'success':true}" +")";
		 }else{
			 //modelMap.addAttribute("delFile", false);
			 return callbackFunName +"("+ "{'success':false}" +")";
		 }
		
	}
	/**
	 * 
	 * @param id  取消在首页置顶显示的新闻id
	 * @param requst 用于请求前台跨域ajax要接收返回数据的js函数
	 * @return ajax返回前台
	 */
	@RequestMapping("/cancelimportantnews")
	@ResponseBody
	public String cancelimportantnews(@RequestParam(value="id",required=true) int id,
			HttpServletRequest request)
	{
		//logger.info(id);
		newsandbulletService.cancelimportantnews(id);
		String callbackFunName = request.getParameter("callbackparam");
		return callbackFunName +"("+ "{'success':true}" +")";
		
	}
	/**
	 * 
	 * @param title   进行模糊匹配的新闻、公告title
	 * @param modelMap 进行前台与后台数据传输的
	 * @param type 类型：新闻（news）或公告(bulletin)
	 * @return  返回查询的结果
	 */
	@RequestMapping("/search")
	public String Search(@RequestParam("title") String title,ModelMap modelMap,@RequestParam("nbtypehi")String type){
		//System.out.println(type + "------");
		int count = newsandbulletService.countofresults(title, type);
		List<newsandbulletin> newses = newsandbulletService.searchnbs(title,
				type, 0, count);
		modelMap.addAttribute("newsesCount", count);
		modelMap.addAttribute("newses", newses);
		path = PathUtil.setPathParams(new String[] { "PackageName:backend",
				"ViewName:newsmag", "ViewTitle:新闻公告管理", "smenu:newsandbullet",
				"mmenu:newsmag" });
		return PathUtil.returnStr(path, modelMap);
	}
}
